<?php

use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\builder\Form;
use cza\base\widgets\ui\adminlte2\InfoBox;
use cza\base\models\statics\EntityModelStatus;
use common\widgets\Gridster\Gridster;
use common\models\c2\statics\CmsBlockLayout;
use yii\widgets\Pjax;
use yii\bootstrap\Dropdown;

$messageName = $model->getMessageName();
$layoutType = yii\helpers\Json::encode(CmsBlockLayout::getHashMap('id', 'defintion'));
?>
<style>
    .text-white{
        color:#fff;
    }
    .myitem{
        min-height:55px;
        background:#4979fe;
        margin-top:10px;
        margin-bottom:10px;
        padding:10px;
        border-right:2px solid #fff;
    }
</style>
<?php
//var_dump( $model->getAllImageUrls());
Pjax::begin(['id' => $model->getDetailPjaxName(), 'linkSelector' => 'false', 'linkSelector' => false, 'formSelector' => $model->getPrefixName('layout-form', true), 'enablePushState' => false,]);

$form = ActiveForm::begin([
            'action' => ['edit', 'id' => $model->id],
            'options' => [
                'id' => $model->getPrefixName('layout-form'),
                'data-pjax' => 0,
        ]]);
?>

<div class="<?= $model->getPrefixName('form') ?>">
    <?php if (Yii::$app->session->hasFlash($messageName)): ?>
        <?php
        if (!$model->hasErrors()) {
            echo InfoBox::widget([
                'withWrapper' => false,
                'messages' => Yii::$app->session->getFlash($messageName),
            ]);
        } else {
            echo InfoBox::widget([
                'defaultMessageType' => InfoBox::TYPE_WARNING,
                'messages' => Yii::$app->session->getFlash($messageName),
            ]);
        }
        ?>
    <?php endif; ?>
    <div class="well" >
        <?php
        // $form->field($model, 'layout_id')->hiddenInput();
        // $form->field($model, 'layout_definition')->hiddenInput(['name'=>'layout_definition','id' => 'layout_definition']);
        echo Form::widget([
            'model' => $model,
            'form' => $form,
            'columns' => 2,
            'attributes' => [
                'layout_definition' => [
                    'type' => Form::INPUT_TEXT,
                ],
                'layout_id' => [
                    'type' => Form::INPUT_DROPDOWN_LIST,
                    'items' => CmsBlockLayout::getHashMap('id', 'label'),
                    'options' => [
                        'onchange' => "renderwidget(this.value)"
                    ]
                ],
            ],
            'options' => [
                'style' => "display:none;"
            ]
        ]);


        echo yii\bootstrap\ButtonGroup::widget([
            'options' => ['style' => ['margin-bottom' => '15px'], 'type' => "button"],
            'buttons' => [
                yii\bootstrap\ButtonDropdown::widget([
                    'label' => Yii::t('app.c2', 'Layout Type'),
                    'containerOptions' => ['style' => ['margin-bottom' => '15px']],
                    'options' => ['class' => 'btn btn-primary'],
                    'dropdown' => [
                        'items' => [
                            ['label' => CmsBlockLayout::getData(CmsBlockLayout::TYPE_DEFAULT, 'label'), 'options' => ['id' => CmsBlockLayout::TYPE_DEFAULT, 'class' => 'active layoutType', 'style' => 'cursor:pointer;']],
                            ['label' => CmsBlockLayout::getData(CmsBlockLayout::TYPE_A,'label'), 'options' => ['id' => CmsBlockLayout::TYPE_A, 'class' => 'layoutType', 'style' => 'cursor:pointer;']],
                            ['label' => CmsBlockLayout::getData(CmsBlockLayout::TYPE_B, 'label'), 'options' => ['id' => CmsBlockLayout::TYPE_B, 'class' => 'layoutType', 'style' => 'cursor:pointer;']],
                            ['label' => CmsBlockLayout::getData(CmsBlockLayout::TYPE_C, 'label'), 'options' => ['id' => CmsBlockLayout::TYPE_C, 'class' => 'layoutType', 'style' => 'cursor:pointer;']],
                            ['label' => CmsBlockLayout::getData(CmsBlockLayout::TYPE_D, 'label'), 'options' => ['id' => CmsBlockLayout::TYPE_D, 'class' => 'layoutType', 'style' => 'cursor:pointer;']],
                            ['label' => CmsBlockLayout::getData(CmsBlockLayout::TYPE_E, 'label'), 'options' => ['id' => CmsBlockLayout::TYPE_E, 'class' => 'layoutType', 'style' => 'cursor:pointer;']],
                        ]
                    ],
                ]),
                ['label' => Yii::t('app.c2', 'Load Images'), 'options' => ['id' => $model->getPrefixName('loadimage'), 'class' => 'btn btn-primary', 'type' => "button"],],
                ['label' => Yii::t('app.c2', 'Save'), 'options' => ['class' => 'btn btn-primary', 'type' => "submit"],],
            ]
        ]);

        $gridster = Gridster::begin([
                    'options' => [
                        'id' => 'album_gridster',
                        'class' => 'gridster',
                        'style' => 'width:800px;',
                    ],
                    'initType' => $model->isNewRecord ? CmsBlockLayout::TYPE_DEFAULT : $model->layout_id,
                    'definition' => $model->layout_definition ? $model->layout_definition : null,
                    'clientOptions' => [
                        'autogenerate_stylesheet' => true,
                        'widget_margins' => [5, 5],
                        'shift_widgets_up' => false,
                        'avoid_overlapped_widgets' => true,
                        // 'auto_init'=>false,
                        'max_cols' => 12,
                        'min_cols' => 1,
                        'collision' => [
                        //'wait_for_mouseup'=>true  
                        ],
                        'responsive_breakpoint' => true,
                        'widget_base_dimensions' => [60, 60],
                        //'autogrow_cols' => true,
                        'resize' => ['enabled' => true, 'resize' => new \yii\web\JsExpression('
                                function(e,p){
                                var li = jQuery(p.$helper).parent()
                                 li.children("img").css({
                                    width:li.width(),
                                    height:li.height()
                                })
                            
                                }')]
                    ]
        ]);
//        $gridster->beginWidget([
//            'data-row' => "1", 'data-col' => "1", 'data-sizex' => "6", 'data-sizey' => "2",
//        ]);
        //echo "<header>Some other text</header> The other widget content";
        //$gridster->endWidget();
        Gridster::end();



        echo Html::beginTag('div', ['class' => 'box-footer']);
        echo Html::submitButton('<i class="fa fa-save"></i> ' . Yii::t('app.c2', 'Save'), ['type' => 'button', 'class' => 'btn btn-primary pull-right']);
        echo Html::a('<i class="fa fa-arrow-left"></i> ' . Yii::t('app.c2', 'Go Back'), ['index'], ['data-pjax' => '0', 'class' => 'btn btn-default pull-right', 'title' => Yii::t('app.c2', 'Go Back'),]);
        echo Html::endTag('div');
        ?>
    </div>
</div>
<?php
ActiveForm::end();
?>

<?php
//$this->registerJsFile('https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js', ['depends' => [\yii\web\AssetBundle::className()]]);

$js = "";
$js .= "
    jQuery(function(){
    
    $('#" . $model->layout_id . "').addClass('bg-primary text-white');    

     jQuery('" . $model->getDetailPjaxName(true) . "').on('submit',function(e){
     console.log(gridster.generate_grid_and_stylesheet ());
     $('#cmsblock-layout_definition').val(JSON.stringify(gridster.serialize())) ;
 
 
})

var images = " . yii\helpers\Json::encode($model->getAllImageUrls()) . ";
$('" . $model->getPrefixName('loadimage', true) . "').on('click',function(){
        
       $.each(images, function(index,item){
         var gridli  = $('#album_gridster li').eq(index);
         if(!gridli){console.log('exit'); return;}
         if(gridli.children('img').length>=1){return; }
          gridli.append('<img src=\"'+item['image-src']+'\" width=\"'+gridli.width()+'px\"  height=\"'+gridli.height()+'px\" />')           

}) 
})
     

//var arr =  sort_by_row_and_col_asc(JSON.parse(widgets))    

        




     $('.layoutType').on('click',function(){

        $('#cmsblock-layout_id').val($(this).attr('id')) ;    
        $('#cmsblock-layout_id').trigger('onchange');
        $('.layoutType').removeClass('bg-primary text-white');
        $(this).addClass('bg-primary text-white');
})

})
";
$this->registerJs($js);
$beginJs = "";
$beginJs .= "
//    
//        function loadImage(path, width, height, target) {
//             $('<img src=\"'+ path +'\">').load(function() {
//               $(this).width(width).height(height).appendTo(target);
//             });
//         }


	function convInt (obj) {
		var props = ['col', 'row', 'size_x', 'size_y'];
		var tmp = {};
		for (var i = 0, len = props.length; i < len; i++) {
			var prop = props[i];
			if (!(prop in obj)) {
				throw new Error('Not exists property `' + prop + '`');
			}
			var val = obj[prop];
			if (!val || isNaN(val)) {
				throw new Error('Invalid value of `' + prop + '` property');
			}
			tmp[prop] = +val;
		}
		return tmp;
	}


      var widgets = " . yii\helpers\Json::encode($model->layout_definition) . ";
   	var sort_by_row_and_col_asc = function (widgets) {
			widgets = widgets.sort(function (a, b) {
			a = convInt(a);
			b = convInt(b);
			if (a.row > b.row || a.row === b.row && a.col > b.col) {
				return 1;
			}
			return -1;
		});
 
		return widgets;
	};
";
$this->registerJs($beginJs, \yii\web\View::POS_BEGIN);
?>
<?php
Pjax::end();
$js = "";
$js .= "jQuery('{$model->getDetailPjaxName(true)}').off('pjax:send').on('pjax:send', function(){jQuery.fn.czaTools('showLoading', {selector:'{$model->getDetailPjaxName(true)}', 'msg':''});});\n";
$js .= "jQuery('{$model->getDetailPjaxName(true)}').off('pjax:complete').on('pjax:complete', function(){jQuery.fn.czaTools('hideLoading', {selector:'{$model->getDetailPjaxName(true)}'});});\n";
$this->registerJs($js);
?>
    

